Solution 1 :using if
$posts = Post::select("*");
if ($request->has('user_id')) {
$posts = $posts->where('user_id', $request->user_id);
}
$posts = $posts->get();
Solution 2 : using when() (Better solution)
$posts = Post::select("*")
->when($request->has('user_id'), function ($query) use ($request) {
$query->where('user_id', $request->user_id);
})
->get();
dd($posts);
If else
$posts = Post::select("*");
if ($request->get('order_by') == "publish_date") {
$posts = $posts->orderBy('publish_date', 'desc');
} else {
$posts = $posts->orderBy('created_at', 'desc');
}
$posts = $posts->get();
Using when()
$posts = Post::select("*")
->when($request->get('order_by') == "publish_date", function ($query) {
return $query->orderBy('publish_date', 'desc');
}, function ($query) {
return $query->orderBy('created_at', 'desc');
})
->get();
dd($posts);
Multiple When()
public function index(Request $request)
{
$posts = Post::select("*")
->when($request->has('user_id'), function ($query) use ($request) {
$query->where('user_id', $request->user_id);
})
->when($request->has('category_id'), function ($query) use ($request) {
$query->where('category_id', $request->category_id);
})
->when($request->has('title'), function ($query) use ($request) {
$query->where('title', 'LIKE', '%' . $request->title .'%');
})
->get();
dd($posts);
}